#!/bin/zsh

# A script to perform incremental backups using rsync

set -o errexit
set -o nounset
set -o pipefail


BACKUP_ROOT="/source/backup"
DATETIME="$(date '+%Y-%m-%d_%H:%M:%S')"

# BACKUP latex_data-sharelatex_data
SOURCE_DIR="/home/fnlp/latex_data/sharelatex_data"
BACKUP_DIR="${BACKUP_ROOT}/latex_data/sharelatex_data"

mkdir -p "${BACKUP_DIR}"
BACKUP_PATH="${BACKUP_DIR}/${DATETIME}"
LATEST_LINK="${BACKUP_DIR}/latest"

rsync -av --delete \
  "${SOURCE_DIR}/" \
  --link-dest "${LATEST_LINK}" \
  --exclude=".cache" \
  "${BACKUP_PATH}"

rm -rf "${LATEST_LINK}"
ln -s "${BACKUP_PATH}" "${LATEST_LINK}"


# BACKUP latex_data-mongodb
docker exec latex_mongo /bin/bash -c "mongodump -o /data/db/backup"

SOURCE_DIR="/home/fnlp/latex_data/mongo_data/backup"
BACKUP_DIR="${BACKUP_ROOT}/latex_data/mongodb"

mkdir -p "${BACKUP_DIR}"
BACKUP_PATH="${BACKUP_DIR}/${DATETIME}"
LATEST_LINK="${BACKUP_DIR}/latest"

rsync -av --delete \
  "${SOURCE_DIR}/" \
  --link-dest "${LATEST_LINK}" \
  --exclude=".cache" \
  "${BACKUP_PATH}"

rm -rf "${LATEST_LINK}"
ln -s "${BACKUP_PATH}" "${LATEST_LINK}"

# BACKUP mongo4
docker exec mongo4 /bin/bash -c "mongodump -o /data/db/backup --username ${DB_USER} --password ${DB_PASSWORD}"

SOURCE_DIR="/home/fnlp/mongo4/backup"
BACKUP_DIR="${BACKUP_ROOT}/mongo4"

mkdir -p "${BACKUP_DIR}"
BACKUP_PATH="${BACKUP_DIR}/${DATETIME}"
LATEST_LINK="${BACKUP_DIR}/latest"

rsync -av --delete \
  "${SOURCE_DIR}/" \
  --link-dest "${LATEST_LINK}" \
  --exclude=".cache" \
  "${BACKUP_PATH}"

rm -rf "${LATEST_LINK}"
ln -s "${BACKUP_PATH}" "${LATEST_LINK}"
